package com.ccs;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.Vector;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class loadTF {

    private String question;
    private String answer;
    public String url = new String();
    private String TFItem;
    public Random randTF = new Random();
    private int[] checker = new int[3];
    private int checkIndex;

    public loadTF(){
        for ( int i = 0; i < 3; i++ ){
            checker[i] = 5;
        }

        checkIndex = 0;
        this.randomizeTF();
    }

    public void randomizeTF(){
        int x = -1;
        boolean check = true;

        while ( checkIndex < 3 ){
            x = randTF.nextInt(4);

            for ( int i = 0; i < 3; i++ ){
                if ( getChecker()[i] == x ){
                    check = false;
                    break;
                }
                check = true;
            }

            if ( check == true ){
                checker[checkIndex] = x;
                checkIndex++;
            }
        }
    }

    public void makeQuery(){
    	url = "http://localhost:8080/TestServer/tf.jsp?tfItem=" + getTFItem();
    	String reply = new String();
    	
    	reply = DownloadText(url);
    	
    	String[] details = split(reply, ",");
        if(details.length == 2){
            this.setQuestion(details[0]);
            this.setAnswer(details[1]);
        }
    }

    //taken from the net.(source: http://tech.groups.yahoo.com/group/DLSU_MAPDEV/files/)
    
    private InputStream OpenHttpConnection(String urlString) throws IOException{
		InputStream in = null;
		int response = -1;            
		URL url = new URL(urlString); 
		URLConnection conn = url.openConnection();    
		if (!(conn instanceof HttpURLConnection))                     
			throw new IOException("Not an HTTP connection");      
		try{
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect(); 

			response = httpConn.getResponseCode();                 
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();                                 
			}                     
		}
		catch (Exception ex){
			throw new IOException("Error connecting");            
		}
		return in;     
	}
    
	private String DownloadText(String URL){
        int BUFFER_SIZE = 2000;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "";
        }
        
        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        
          String str = "";
          char[] inputBuffer = new char[BUFFER_SIZE];          
        try {
            while ((charRead = isr.read(inputBuffer))>0){                    
                //---convert the chars to a String---
                String readString = 
                    String.copyValueOf(inputBuffer, 0, charRead);                    
                str += readString;
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }    
        return str;        
    }
    
    /*  Method for splitting since StringTokenizer is not available in J2ME.
     *  Taken from the 'Net.
     */

    public String[] split(String splitStr, String delimiter) {
        StringBuffer token = new StringBuffer();
        Vector tokens = new Vector();
        // split
        char[] chars = splitStr.toCharArray();
        for (int i=0; i < chars.length; i++) {
            if (delimiter.indexOf(chars[i]) != -1) {
                // we bumbed into a delimiter
                if (token.length() > 0) {
                    tokens.addElement(token.toString());
                    token.setLength(0);
                }
            } else {
                token.append(chars[i]);
            }
        }
        // don't forget the "tail"...
        if (token.length() > 0) {
            tokens.addElement(token.toString());
        }
        // convert the vector into an array
        String[] splitArray = new String[tokens.size()];
        for (int i=0; i < splitArray.length; i++) {
            splitArray[i] = (String)tokens.elementAt(i);
        }
        return splitArray;
    }

    /**
     * @return the question
     */
    public String getQuestion() {
        return question;
    }

    /**
     * @param question the question to set
     */
    public void setQuestion(String question) {
        this.question = question;
    }

    /**
     * @return the checker
     */
    public int[] getChecker() {
        return checker;
    }

    /**
     * @return the TFItem
     */
    public String getTFItem() {
        return TFItem;
    }

    /**
     * @param TFItem the TFItem to set
     */
    public void setTFItem(String TFItem) {
        this.TFItem = TFItem;
    }

    /**
     * @return the answer
     */
    public String getAnswer() {
        return answer;
    }

    /**
     * @param answer the answer to set
     */
    public void setAnswer(String answer) {
        this.answer = answer;
    }

}
